package service

import (
	"context"
	"gitee.com/hxchjm/go-admin/internal/dao"
	"gitee.com/hxchjm/go-admin/internal/models"
	"gitee.com/hxchjm/go-admin/pkg/jwtauth"
	"github.com/hxchjm/log"
)

type Menu struct {
}

func (r Menu) GetPage(ctx context.Context, req *models.ReqMenuGetPage) (any, error) {
	res, err := dao.SysMenu{}.GetPage(ctx, req)
	if err != nil {
		return nil, err
	}

	var resp []models.SysMenu
	for _, v := range res {
		resp = append(resp, v)
	}
	/*rsp = &models.RspMenuGetPage{}
	for _, v := range res {
		rsp.List = append(rsp.List, v)
	}*/
	return resp, nil
}
func (r Menu) Get(ctx context.Context, req *models.ReqMenuGet) (rsp interface{}, err error) {
	rsp, err = dao.SysMenu{SysMenu: models.SysMenu{MenuId: int(req.Id)}}.Get(ctx)
	if err != nil {
		return nil, err
	}
	return
}
func (r Menu) Insert(ctx context.Context, req *models.ReqMenuInsert) (rsp any, err error) {
	req.CreateBy = jwtauth.GetClaims(ctx).UID
	if err = (dao.SysMenu{SysMenu: *req}).Insert(ctx); err != nil {
		log.Errorf(ctx, "Menu Insert err (%+v)", err)
		return
	}
	return
}
func (r Menu) Update(ctx context.Context, req *models.ReqMenuUpdate) (rsp any, err error) {
	req.UpdateBy = jwtauth.GetClaims(ctx).UID
	if err = (dao.SysMenu{SysMenu: *req}).Update(ctx); err != nil {
		log.Errorf(ctx, "Menu Update err (%+v)", err)
		return
	}
	return
}
func (r Menu) Delete(ctx context.Context, req *models.ReqMenuDelete) (rsp any, err error) {
	if err = (dao.SysMenu{}).Delete(ctx, req.Ids); err != nil {
		return
	}
	return
}

// GetMenuRole 根据登录角色名称获取菜单列表数据（左菜单使用）
// @Summary 根据登录角色名称获取菜单列表数据（左菜单使用）
// @Description 获取JSON
// @Tags 菜单
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/menurole [get]
// @Security Bearer
/*func (r Menu) GetMenuRole(ctx context.Context) (any, error) {
	result, err := dao.SysMenu{}.GetRoleMenu(jwtauth.GetClaims(ctx).RoleKey)
	if err != nil {
		log.Errorf(ctx, "查询失败,err(%+v)", err)
		return nil, err
	}
	return result, nil
}*/

// GetMenuTreeSelect 根据角色ID查询菜单下拉树结构
// @Summary 角色修改使用的菜单列表
// @Description 获取JSON
// @Tags 菜单
// @Accept  application/json
// @Product application/json
// @Param roleId path int true "roleId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/menuTreeselect/{roleId} [get]
// @Security Bearer
func (r Menu) GetMenuTreeSelect(ctx context.Context, req *models.ReqSelectRole) (*models.RspSelectRole, error) {
	rsp := &models.RspSelectRole{}
	result, err := dao.SysMenu{}.SetLabel(ctx)
	if err != nil {
		log.Errorf(ctx, "查询失败, err(%+v)", err)
		return nil, err
	}

	menuIds := make([]int, 0)
	if req.RoleId != 0 {
		menuIds, err = dao.SysRole{}.GetRoleMenuId(req.RoleId)
		if err != nil {
			log.Errorf(ctx, "Menu GetRoleMenuId err(%+v),req(%+v)", err, req)
			return nil, err
		}
	}
	rsp.Menus = result
	rsp.CheckedKeys = menuIds
	return rsp, nil
}
